<?php

class ShiftController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column3';


	public $sidebarMenu=array(
								array('label'=>'Roster Control', 'url'=>array('/roster/index')),
								array('label'=>'Shift Changes', 'url'=>array('/shiftChange/management')),
								array('label'=>'User Schedules', 'url'=>array('/schedule/index')),
								array('label'=>'Maintenance', 'url'=>array('/site/maintenance')),
								array('label'=>'Reporting', 'url'=>array('/site/reporting')),
							);

	protected function beforeAction($action) {
		$this->links =  Links::getTeamLinks(Yii::app()->user->team_id);
		
		if(empty($this->links)) {
			$this->links = array(array('label'=>'---','url'=>'#'));
			return true;
		} else
			return true;
	}						
	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(

			array('allow', // allow admin user to perform the following actions
				'actions'=>array('admin','delete','create','update','view'),
				'users'=>array('@'),
				'expression'=>'$user->can_create_edit_shifts == 1',
			),
			array('allow', 
				'actions'=>array('index','my_Shifts','team_Shifts'),
				'users'=>array('@'),
				'expression'=>'$user->can_create_shift_change == 1',
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Shift;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Shift']))
		{
			$model->attributes=$_POST['Shift'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->idshift));
		}
		
		$model->team_id = Yii::app()->user->team_id;

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Shift']))
		{
			$model->attributes=$_POST['Shift'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->idshift));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}


	public function actionIndex()
	{
		$this->sidebarMenu=array(
								array('label'=>'My Shifts', 'url'=>array('/shift/my_shifts')),
								array('label'=>'Team Shifts', 'url'=>array('/shift/team_shifts')),
								array('label'=>'Shift Changes', 'url'=>array('/shiftChange/change_management')),
								);		
		$this->render('index');
	}

	public function actionMy_Shifts()
	{
		$this->sidebarMenu=array(
								array('label'=>'My Shifts', 'url'=>array('/shift/my_shifts')),
								array('label'=>'Team Shifts', 'url'=>array('/shift/team_shifts')),
								array('label'=>'Shift Changes', 'url'=>array('/shiftChange/change_management')),
								);	
		$model=new Schedule('search');
		$model->unsetAttributes();  // clear any default values		
		$model->iduser = User::model()->findByAttributes(array('username'=>Yii::app()->user->id))->iduser;
		
		$this->render('my_shifts', array( 'model'=>$model));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Shift('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Shift']))
			$model->attributes=$_GET['Shift'];
		
		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Shift the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Shift::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Shift $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='shift-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

	public function getWeekSchedulesGrid($team, $week, $year) {
		
		///<<<<<<----------------GET RELEVANT USERS  ------------------------------------------------------------->>>>
		
		// get list of enabled users 
		$users = User::model()->findAll(array('condition'=>'enabled = 1 and team = '.$team));
		
		///<<<<<<----------------DEFINE RELEVANT DATES------------------------------------------------------------->>>>
		$week_start = new DateTime();
		$week_start->setISODate($year,$week);
		
		//creating an array with dayOfWeek => date entries
		$daysArray = array();
		$daysArray['monday'] = $week_start->format('Y-m-d');
		$daysArray['tuesday'] = date('Y-m-d', strToTime('next Tuesday '.$week_start->format('Y-m-d')));
		$daysArray['wednesday'] = date('Y-m-d', strToTime('next Wednesday '.$week_start->format('Y-m-d')));
		$daysArray['thursday'] = date('Y-m-d',  strToTime('next Thursday '.$week_start->format('Y-m-d')));
		$daysArray['friday'] = date('Y-m-d',  strToTime('next Friday '.$week_start->format('Y-m-d')));
		$daysArray['saturday'] = date('Y-m-d',  strToTime('next Saturday '.$week_start->format('Y-m-d')));
		$daysArray['sunday'] = date('Y-m-d',  strToTime('next Sunday '.$week_start->format('Y-m-d')));
		
		
		///<<<<<<----------------DEFINE GLOBAL DATA CONTAINERS------------------------------------------------------------->>>>
		$rows = array();
				
		///<<<<<<----------------ITERATE THROUGH USERS------------------------------------------------------------->>>>
		foreach ($users as $user) {
			
			///<<<<<<----------------DEFINE USER DATA CONTAINER ARRAY------------------------------------------------------------->>>>
			$userRow = array();
			$userRow['iduser'] = $user->iduser;
			$userRow['batch'] = $user->batch;
			$userRow['username'] = $user->username;
			
			//Fills all days with the respective date and null value; days will be updated later if schedules for that day exist
			$userRow['monday'] = '---';
			$userRow['mondayDate'] = $daysArray['monday'];
			$userRow['tuesday'] = '---';
			$userRow['tuesdayDate'] = $daysArray['tuesday'];
			$userRow['wednesday'] = '---';
			$userRow['wednesdayDate'] = $daysArray['wednesday'];
			$userRow['thursday'] = '---';
			$userRow['thursdayDate'] = $daysArray['thursday'];
			$userRow['friday'] = '---';
			$userRow['fridayDate'] = $daysArray['friday'];
			$userRow['saturday'] = '---';
			$userRow['saturdayDate'] = $daysArray['saturday'];
			$userRow['sunday'] = '---';
			$userRow['sundayDate'] = $daysArray['sunday'];
				
			///<<<<<<----------------GET SCHEDULE PER DAY------------------------------------------------------------->>>>
			$userWeekSchedule = Schedule::getUserWeekSchedule($user->iduser,true,$week,$year);
			
			if($userWeekSchedule!=null) {			
				foreach ($userWeekSchedule as $schedule) {
			
				///<<<<<<----------------ADD DAY ARRAY TO USER ARRAY------------------------------------------------------------->>>>
				///<<<<<<----------------ASSIGN PARAMETERS TO DAY ARRAY------------------------------------------------------------->>>>
					if($schedule->idweekday == Weekday::MONDAY) {
						$userRow['monday'] = $schedule->shift_relation->name;
						if($schedule->isQshiftChange)
							$userRow['monday'] .= "*";
						elseif($schedule->wasChanged)
							$userRow['monday'] .= "**";
					} elseif ($schedule->idweekday == Weekday::TUESDAY) {
						$userRow['tuesday'] = $schedule->shift_relation->name;	
						if($schedule->isQshiftChange)
							$userRow['tuesday'] .= "*";
						elseif($schedule->wasChanged)
							$userRow['tuesday'] .= "**";		
					} elseif ($schedule->idweekday == Weekday::WEDNESDAY) {
						$userRow['wednesday'] = $schedule->shift_relation->name;
						if($schedule->isQshiftChange)
							$userRow['wednesday'] .= "*";
						elseif($schedule->wasChanged)
							$userRow['wednesday'] .= "**";			
					} elseif ($schedule->idweekday == Weekday::THURSDAY) {
						$userRow['thursday'] = $schedule->shift_relation->name;	
						if($schedule->isQshiftChange)
							$userRow['thursday'] .= "*";
						elseif($schedule->wasChanged)
							$userRow['thursday'] .= "**";		
					} elseif ($schedule->idweekday == Weekday::FRIDAY) {
						$userRow['friday'] = $schedule->shift_relation->name;
						if($schedule->isQshiftChange)
							$userRow['friday'] .= "*";
						elseif($schedule->wasChanged)
							$userRow['friday'] .= "**";		
					} elseif ($schedule->idweekday == Weekday::SATURDAY) {
						$userRow['saturday'] = $schedule->shift_relation->name;	
						if($schedule->isQshiftChange)
							$userRow['saturday'] .= "*";
						elseif($schedule->wasChanged)
							$userRow['saturday'] .= "**";		
					} elseif ($schedule->idweekday == Weekday::SUNDAY) {
						$userRow['sunday'] = $schedule->shift_relation->name;
						if($schedule->isQshiftChange)
							$userRow['sunday'] .= "*";
						elseif($schedule->wasChanged)
							$userRow['sunday'] .= "**";		
					}			
				}					
			}
			///<<<<<<----------------ADD USER ARRAY TO GLOBAL ARRAY------------------------------------------------------------->>>>
			
			$rows[] = $userRow;
		
		} //ends forearch user
		
		///<<<<<<----------------FINAL GLOBAL ARRAY DETAILS------------------------------------------------------------->>>>
		
			
		///<<<<<<----------------RETURN FINAL GLOBAL PROVIDER/ARRAY ------------------------------------------------------------->>>>
		
		
			$dataProvider=new CArrayDataProvider($rows, array(
				'keyField'=>'iduser',
				/*
				'sort'=>array(
					'attributes'=>array(
						 'id', 'username', 'email',
					),
				), */
				'pagination'=>array(
					'pageSize'=>100,
				),
			));
			
			return $dataProvider;		
	}
	
	public function actionTeam_Shifts($week=null,$year=null)
	{
		$this->sidebarMenu=array(
									array('label'=>'My Shifts', 'url'=>array('/shift/my_shifts')),
									array('label'=>'Team Shifts', 'url'=>array('/shift/team_shifts')),
									array('label'=>'Shift Changes', 'url'=>array('/shiftChange/change_management')),
								);	

		//Yii::app()->user->team_id
		
		if($week==null) {
			$dateObject = new DateTime('NOW');
			$dateObject->setTimeZone(new DateTimeZone("America/Costa_Rica"));
			$week  = $dateObject->format('W');
			$year = $dateObject->format('Y');
		}
		
		$this->render('team_shifts',
					  array(
						'week'=>$week,
						'year'=>$year
					  )
					);
	}
}
